package com.qk.management.config;

import com.qk.management.service.ReportService;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component
@Order(1)
public class ConditionalRedisPreloader implements ApplicationRunner {

    private static final Logger logger = LoggerFactory.getLogger(ConditionalRedisPreloader.class);

    private final ReportService reportService;

    @Value("${spring.data.redis.preload.enabled:true}")
    private boolean preloadEnabled;

    public ConditionalRedisPreloader(RedisTemplate<String, Object> redisTemplate,
                                     ReportService reportService) {
        this.reportService = reportService;
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        if (!preloadEnabled) {
            logger.info("Redis数据预热已禁用");
            return;
        }

        logger.info("开始执行Redis数据预热...");
        preloadCriticalData();
        preloadReportData(); // 添加报表数据预热
    }

    private void preloadCriticalData() {
        // 只预热关键数据
        logger.info("预热关键数据到Redis");
    }

    private void preloadReportData() {
        try {
            logger.info("开始预热报表数据...");
            // 执行 ReportService.getOverview() 方法触发缓存
            reportService.getOverview();
            logger.info("报表数据预热完成");
        } catch (Exception e) {
            logger.error("报表数据预热失败", e);
        }
    }
}
